import { _decorator, Component, Node, Sprite, UITransform } from 'cc'
import { TILE_CONFIGS } from '../utils/constants'
import { ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, EVENT_NAME_ENUM, SPIKES_TYPE_MAP_TOTAL_COUNT_ENUM } from '../enums'
import { ISpikes } from '../levels'
import { StateMachine } from '../base/StateMachine'
import { generateUUID } from '../utils'
import { SpikesStateMachine } from './SpikesStateMachine'
import EventMgr from '../runtime/EventMgr'
import DataMgr from '../runtime/DataMgr'
const { ccclass, property } = _decorator
/** 地刺 */

@ccclass('SpikesMgr')
export class SpikesMgr extends Component {
  /** 实体id */
  id: string = generateUUID()
  /** 当前实体X轴位置 */
  x: number = 0
  /** 当前实体Y轴位置 */
  y: number = 0
  /** 状态机 */
  fsm: StateMachine
  /** 实体类型 */
  type: ENTITY_TYPE_ENUM

  /** 当前地刺数量 */
  private _count: number
  public get count(): number {
    return this._count
  }
  public set count(value: number) {
    this._count = value
    this.fsm.setParams(ENTITY_STATE_ENUM.SPIKES_CUR_COUNT, value) // 通过当前状态触发动画的执行 使数据和UI进行分离
  }

  /** 地刺总数量 */
  private _totalCount: number
  public get totalCount(): number {
    return this._totalCount
  }
  public set totalCount(value: number) {
    this._totalCount = value
    this.fsm.setParams(ENTITY_STATE_ENUM.SPIKES_TOTAL_COUNT, value) // 通过当前状态触发动画的执行 使数据和UI进行分离
  }

  async init(params: ISpikes) {
    // 添加精灵组件
    const sprite = this.addComponent(Sprite)
    sprite.sizeMode = Sprite.SizeMode.CUSTOM // 设置精灵大小模式为自定义
    // 设置组件大小为瓦片的4倍
    const transform = this.getComponent(UITransform)
    transform.setContentSize(TILE_CONFIGS.TILE_WIDTH * 4, TILE_CONFIGS.TILE_HEIGHT * 4)
    // 添加状态机
    this.fsm = this.addComponent(SpikesStateMachine)
    await this.fsm.init() // 初始化状态机参数
    // 接收外部传递的参数
    this.x = params.x
    this.y = params.y
    this.type = params.type
    this.count = params.count // 当前地刺数量
    this.totalCount = SPIKES_TYPE_MAP_TOTAL_COUNT_ENUM[this.type] // 地刺总数

    EventMgr.Instance.on(EVENT_NAME_ENUM.PLAYER_MOVE_END, this.onLoop, this)
  }

  update() {
    // 横纵坐标要偏移1.5个瓦片才会在目标位置
    this.node.setPosition(
      this.x * TILE_CONFIGS.TILE_WIDTH - TILE_CONFIGS.TILE_WIDTH * 1.5,
      this.y * TILE_CONFIGS.TILE_HEIGHT + TILE_CONFIGS.TILE_HEIGHT * 1.5,
    )
  }

  onLoop() {
    if (this.count === this.totalCount) {
      this.count = 1
    } else {
      this.count++
    }

    this.onAttack()
  }

  onAttack() {
    if (!DataMgr.Instance.player) return
    const { x: playerX, y: playerY } = DataMgr.Instance.player
    if (this.x === playerX && this.y === playerY && this.count === this.totalCount) {
      EventMgr.Instance.emit(EVENT_NAME_ENUM.ATTACK_PLAYER, ENTITY_STATE_ENUM.DEATH)
    }
  }

  resetSpikes() {
    this.count = 0
  }

  protected onDestroy(): void {
    EventMgr.Instance.off(EVENT_NAME_ENUM.PLAYER_MOVE_END, this.onLoop)
  }
}
